package com.ys.erp.framework.config;

import com.ys.erp.framework.response.ResponseOpenHandler;
import org.apache.tomcat.util.threads.VirtualThreadExecutor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 开启异步
 *
 * @author lwj
 * @date 2021/4/30
 */

@EnableAsync
@SpringBootConfiguration
@Conditional(ResponseOpenHandler.class)
public class ExecutorConfig implements AsyncConfigurer {

//    /**
//     * 线程配置
//     *
//     * @return 线程池
//     */
//    @Bean
//    @Primary
//    public AsyncTaskExecutor applicationTaskExecutor() {
//        VirtualThreadExecutor virtualThreadExecutor = new VirtualThreadExecutor("ys-virtual-thread");
//        return new TaskExecutorAdapter(virtualThreadExecutor);
//    }
//
//    @Bean
//    @Primary
//    public TomcatProtocolHandlerCustomizer<?> threadExecutor() {
//        VirtualThreadExecutor virtualThreadExecutor = new VirtualThreadExecutor("ys-virtual-tomcat-thread");
//        return protocolHandler -> protocolHandler.setExecutor(
//                virtualThreadExecutor
//        );
//    }
    private Integer corePoolSize;

    private Integer maxPoolSize;

    private Integer keepAliveSeconds;

    /**
     * 线程配置
     *
     * @return 线程池
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(20);
        //最大线程数
        executor.setMaxPoolSize(60);
        //队列容量
        executor.setQueueCapacity(600);
        //活跃时间
        executor.setKeepAliveSeconds(300);
        //线程名字前缀
        executor.setThreadNamePrefix("cats-thread-");
        /*
            当poolSize已达到maxPoolSize，如何处理新任务（是拒绝还是交由其它线程处理）
            CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
